package session

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"go_my_framework/app/core/config"
)

func EnableCookieSession(key string) gin.HandlerFunc {
	store := cookie.NewStore([]byte(key))
	store.Options(sessions.Options{Path: "/", MaxAge: 6 * 3600})
	return sessions.Sessions("_SESSION", store)
}

func EnableRedisSession(key string) gin.HandlerFunc {
	store, _ := redis.NewStore(
		10,
		"tcp",
		config.Instance().Redis.Addr,
		config.Instance().Redis.Password,
		[]byte(key))
	store.Options(sessions.Options{Path: "/", MaxAge: 6 * 3600})
	return sessions.Sessions("_SESSION", store)
}

func Set(c *gin.Context, key interface{}, value interface{}) error {
	s := sessions.Default(c)
	s.Set(key, value)
	return s.Save()
}

func Get(c *gin.Context, key interface{}) interface{} {
	s := sessions.Default(c)
	return s.Get(key)
}

func Del(c *gin.Context, key interface{}) error {
	s := sessions.Default(c)
	s.Delete(key)
	return s.Save()
}